//
//  CLTabBarItem.swift
//  CLWeibo
//
//  Created by 陈亮 on 16/7/13.
//  Copyright © 2016年 陈亮. All rights reserved.
//

import UIKit

class CLTabBarItem: UITabBarItem {

    override var badgeValue:String? {
        didSet {
            //通过KVC获取对应的_target对象 也就是CLMainViewController
            let tabBarController = valueForKey("_target") as? UITabBarController
            
            //通过层层循环遍历出我们想要的
            for tabBarChild in tabBarController!.tabBar.subviews{
                
                if tabBarChild.isKindOfClass(NSClassFromString("UITabBarButton")!){
                    for tabBarButtonChild in tabBarChild.subviews {
                        if
                            tabBarButtonChild.isKindOfClass(NSClassFromString("_UIBadgeView")!) {
                                for badgeViewChild in tabBarButtonChild.subviews {
                                    
                                    if badgeViewChild.isKindOfClass(NSClassFromString("_UIBadgeBackground")!){
                                        print("fuck 找你找得好辛苦")
                                         //统计我们这个类里有多少个成员变量
                                        var count :UInt32 = 0
                                        //获取里面的成员列表
                                        let ivars = class_copyIvarList(NSClassFromString("_UIBadgeBackground")!, &count)
                                        for i in 0..<count {
                                            //获取指定位置的成员
                                            let ivar = ivars[Int(i)]
                                            //获取成员姓名
                                            let name = ivar_getName(ivar)
                                            let type = ivar_getTypeEncoding(ivar)
                                            //把获取成员的名字转换成字符串
                                            let nameStr = String(CString: name, encoding: NSUTF8StringEncoding)
                                            let typeStr = String(CString: type, encoding: NSUTF8StringEncoding)
                                            print(nameStr)
                                            print(typeStr)
                                            //使用KVC方式给image赋值
                                            if nameStr == "_image"{
                                                badgeViewChild.setValue(UIImage(named: "main_badge"), forKey: "_image")
                                        }
                                    }
                                }
                        }
                    }
                }
            }
        }
    }
    
}
}

